/**
 * Orienteering Sport Diary Copyright (C) 2009 OSDiary Team
 *
 * This file is part of Orienteering Sport Diary (OSDiary).
 *
 * OSDiary is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see http://www.gnu.org/licenses/.
 */

package org.actions;

import com.opensymphony.xwork2.ActionSupport;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.util.SportsmenDAO;

/**
 *
 * @author George.Mavchun
 */
public class MailAction extends ActionSupport {
    private String email;
    private String result;
    
    public String getMailCheckResult() {
        return result;
    }
    
    public void setEmail(String email) {
        this.email = email;
    }
    
    /**
     *  
     * This method checks if email already exists in database and check it using regular exprestion.
     * Set valid as 'true' if email is valid and doesn`t exist in database.
     * Set valid as 'false' if email is not valid or exists in database.
     * @return String - action result.
     */
    public String validation() {
        boolean valid = checkEmailWithRegExp(email) && !SportsmenDAO.isEmailInDatabase(email);
        if (valid) {
            this.result = "true";
        } else {
            this.result = "false";
        }
        return SUCCESS;
    }
    
    /**
     *  
     * This method checks if email exists in database.
     * Set valid as 'true' if email exists in database.
     * Set valid as 'false' if email doesn`t exist in database.
     * @return String valid
     */
    public String exists() {
        if (SportsmenDAO.isEmailInDatabase(email)) {
            result = "true";
        } else {
            result = "false";
        }
        return SUCCESS;
    }
    
    @Override
    public String execute() {    
        return SUCCESS;
    }
    
    
    /**
     *
     * Check E-mail address using regular exprestion.
     * @param email - E-mail address to check.
     * @return boolean - 'true' if email matches regexp. 
     */
    private boolean checkEmailWithRegExp(String email) {
        Pattern pattern = Pattern.compile("^\\w+[\\w-\\.]*\\@\\w+((-\\w+)|(\\w*))\\.[a-z]{2,3}$");
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }
}
